package com.oreilly.ez.fileserver.web;


import com.oreilly.ez.fileserver.base.R;
import com.oreilly.ez.fileserver.base.YmlConfig;
import com.oreilly.ez.fileserver.entity.FileInfo;
import com.oreilly.ez.fileserver.service.FileService;
import com.oreilly.ez.fileserver.service.impl.FileInfoService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Api
@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/files")
public class FileCtrl extends BaseCtrl<FileInfo>{




    @Autowired
    private YmlConfig ymlConfig;

    @Autowired
    private FileInfoService fileInfoService;

    @Autowired
    private FileService fileService;


    @GetMapping("/testPath")
    public Object testPath() throws Exception{

//        String path = ResourceUtils.getURL("classpath:").getPath();

        File root = new File(ResourceUtils.getURL("classpath:").getPath());
        if(!root.exists()){
            root = new File("");
        }
        System.out.println("root:" + root.getAbsolutePath());

        File upload = new File(root.getAbsolutePath(), "static/uploads/");

        if(!upload.exists()){
            upload.mkdirs();
        }

        String uploadAbsolutePath = upload.getAbsolutePath();
        System.out.println(uploadAbsolutePath);

        File testFile = new File(uploadAbsolutePath, "test.txt");

        FileUtils.write(testFile, "hello " +System.currentTimeMillis());

        return R.ok(uploadAbsolutePath);
    }




    @PostMapping(value = "/upload")
    public Object upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "文件为空";
        }


        // 获取文件名
        String fileName = file.getOriginalFilename();
        log.info("上传的文件名为：" + fileName);

        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.info("上传的后缀名为：" + suffixName);


        // 文件上传路径
        File dir = new File(System.getProperty("user.dir"), ymlConfig.getUploadDir());


        // 解决中文问题，liunx下中文路径，图片显示问题
         String destName = UUID.randomUUID() + suffixName;

        File dest = new File(dir, destName);

        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        try {

            file.transferTo(dest);
            FileInfo fileInfo = new FileInfo();
            String sid = UUID.randomUUID().toString();
            fileInfo.setSid(sid);
            fileInfo.setAac001(fileName);
            fileInfo.setAac002(destName);

            return R.ok(fileInfo);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.err("上传失败");
    }




    @PostMapping(value = "/new-upload")
    public Object newUpload(@RequestParam("file") MultipartFile file, String cate) throws Exception {
        if (file.isEmpty()) {
            return "文件为空";
        }

        String aac003 = "new-upload";
        if(cate !=null){
            aac003 = cate;
        }

        // 获取文件名
        String fileName = file.getOriginalFilename();
        log.info("上传的文件名为：" + fileName);

        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.info("上传的后缀名为：" + suffixName);


        // 文件上传路径
        File dir = new File(System.getProperty("user.dir"), ymlConfig.getUploadDir());


        // 解决中文问题，liunx下中文路径，图片显示问题
        String destName = UUID.randomUUID() + suffixName;

        File dest = File.createTempFile("file-", suffixName, dir);

        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        try {

            file.transferTo(dest);
            FileInfo fileInfo = new FileInfo();
            String sid = UUID.randomUUID().toString();
            fileInfo.setSid(sid);
            fileInfo.setAac001(fileName);
            fileInfo.setAac002(dest.getName());
            fileInfo.setAac003(aac003);
            fileInfoService.add(fileInfo);

            return R.ok(fileInfo);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.err("上传失败");
    }


    @Override
    Object find(FileInfo item, @PageableDefault Pageable pageable) throws Exception {

        Page<FileInfo> fileInfoPage = fileInfoService.find(item, pageable);
        return R.ok(fileInfoPage);
    }

    @Override
    Object findById(String id) throws Exception {
        return null;
    }

    @Override
    Object add(FileInfo item) throws Exception {
        return null;
    }


    @Override
    Object update(FileInfo item) throws Exception {
        return null;
    }

    @Override
    Object delete(String[] ids) throws Exception {

        fileInfoService.deleteByIds(ids);
        return R.ok("delete ok");
    }
//    @GetMapping()
//    public Object all(){
//
//        List<FileInfo> fileInfoList = fileInfoService.all();
//        return R.ok(fileInfoList);
//    }


    /**
     * 测试下载文件
     * @param fileName
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping("/download/{fileName:.*}")
    public Object download(@PathVariable String fileName, HttpServletRequest request) throws Exception {


        Resource resource = fileService.loadFileAsResource(fileName);
        String contentType = null;

        contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());

        if(contentType == null){

            contentType = "application/octet-stream";
        }

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);



    }
}
